import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import os.path

import pymongo
from pymongo import MongoClient


from tornado.options import define,options
define("port",default=8888,help="run on the given port",type=int)


class Application(tornado.web.Application):
	def __init__(self):
		handlers = [
			(r"/", IndexHandler),
			(r"/wordquery", WordHandler)
		]
		client = MongoClient("127.0.0.1",27017)
		self.db = client.bob
		settings = dict(
			template_path = os.path.join(os.path.dirname(__file__), "templates"),
			static_path=os.path.join(os.path.dirname(__file__), "static"),
		)
		tornado.web.Application.__init__(self,handlers,debug=True,**settings)

class IndexHandler(tornado.web.RequestHandler):
	def get(self):
		self.render('index.html',content="NULL")


class WordHandler(tornado.web.RequestHandler):

	def get(self):
		coll = self.application.db.words
		word = self.get_argument('word')
		word_doc = coll.find_one({"word":word})
		if word_doc:
			del word_doc['_id']
			self.render('index.html',content=word_doc)
		else:
			self.set_status(404)
			self.render('index.html',content="Word not found")	

	def post(self):
		coll = self.application.db.words
		word = self.get_argument('word').strip()
		definition = self.get_argument('definition').strip()
		word_doc = coll.find_one({"word":word})
		if len(definition) == 0 or len(word) == 0:
			self.render('index.html',content="Word and definition can not be null")
		else:
			if word_doc:
				word_doc['definition'] = definition
				coll.save(word_doc)
				self.render('index.html',content="Word already exits,so update the define")
			else:
				word_doc = {'word':word,'definition':definition}
				coll.insert_one(word_doc)
				self.render('index.html',content="add new word success")
		

if __name__ == "__main__":
	tornado.options.parse_command_line()
	http_server = tornado.httpserver.HTTPServer(Application())
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()
